package com.zenithmind.library.service.facade;

import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.library.pojo.dto.AuthorCreateDTO;
import com.zenithmind.library.pojo.dto.BookCreateDTO;
import com.zenithmind.library.pojo.dto.BorrowBookDTO;
import com.zenithmind.library.pojo.dto.ReservationCreateDTO;
import com.zenithmind.library.pojo.query.AuthorQuery;
import com.zenithmind.library.pojo.query.BookQuery;
import com.zenithmind.library.pojo.query.BorrowRecordQuery;
import com.zenithmind.library.pojo.query.ReservationQuery;
import com.zenithmind.library.pojo.vo.*;
import com.zenithmind.library.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 图书馆服务门面
 * 遵循依赖倒置原则：依赖抽象接口而不是具体实现
 * 遵循迪米特法则：减少客户端与多个服务的直接交互
 * 
 * @author ZenithMind
 * @since 2024-06-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LibraryServiceFacade {

    // 依赖抽象接口，而不是具体实现
    private final AuthorQueryService authorQueryService;
    private final AuthorManagementService authorManagementService;
    private final BookQueryService bookQueryService;
    private final BookManagementService bookManagementService;
    private final BookInventoryService bookInventoryService;
    private final BorrowService borrowService;
    private final ReservationService reservationService;

    /**
     * 综合搜索图书馆资源
     * 
     * @param keyword 关键词
     * @param limit 限制数量
     * @return 搜索结果
     */
    public LibrarySearchResultVO searchLibraryResources(String keyword, Integer limit) {
        log.info("综合搜索图书馆资源，关键词：{}，限制数量：{}", keyword, limit);
        
        LibrarySearchResultVO result = new LibrarySearchResultVO();
        
        try {
            // 搜索图书
            BookQuery bookQuery = new BookQuery();
            bookQuery.setSize(limit);
            PageResult<BookVO> books = bookQueryService.searchBooks(keyword, bookQuery);
            result.setBooks(books.getRecords());
            
            // 搜索作者
            result.setAuthors(authorQueryService.searchAuthors(keyword, limit));
            
            return result;
        } catch (Exception e) {
            log.error("搜索图书馆资源失败", e);
            return new LibrarySearchResultVO();
        }
    }

    /**
     * 获取用户的图书馆概览
     * 
     * @param userId 用户ID
     * @return 概览信息
     */
    public UserLibraryOverviewVO getUserLibraryOverview(String userId) {
        log.info("获取用户图书馆概览，用户ID：{}", userId);
        
        UserLibraryOverviewVO overview = new UserLibraryOverviewVO();
        
        try {
            // 获取用户当前借阅记录
            BorrowRecordQuery borrowQuery = new BorrowRecordQuery();
            borrowQuery.setUserId(userId);
            borrowQuery.setStatus(0); // 借阅中
            PageResult<BorrowRecordVO> currentBorrows = borrowService.getBorrowRecordPage(borrowQuery);
            overview.setCurrentBorrows(currentBorrows.getRecords());
            
            // 获取用户当前预约记录
            ReservationQuery reservationQuery = new ReservationQuery();
            reservationQuery.setUserId(userId);
            reservationQuery.setStatus(0); // 预约中
            PageResult<ReservationVO> currentReservations = reservationService.getReservationPage(reservationQuery);
            overview.setCurrentReservations(currentReservations.getRecords());
            
            // 获取推荐图书
            BookQuery bookQuery = new BookQuery();
            bookQuery.setSize(5);
            PageResult<BookVO> recommendedBooks = bookQueryService.getRecommendedBooks(bookQuery);
            overview.setRecommendedBooks(recommendedBooks.getRecords());
            
            return overview;
        } catch (Exception e) {
            log.error("获取用户图书馆概览失败，用户ID：{}", userId, e);
            return new UserLibraryOverviewVO();
        }
    }

    /**
     * 快速借阅图书
     * 
     * @param userId 用户ID
     * @param bookId 图书ID
     * @return 借阅结果
     */
    public Result<BorrowRecordVO> quickBorrowBook(String userId, String bookId) {
        log.info("快速借阅图书，用户ID：{}，图书ID：{}", userId, bookId);
        
        try {
            // 检查图书库存
            if (!bookInventoryService.isStockSufficient(bookId, 1)) {
                return Result.fail("图书库存不足");
            }
            
            // 创建借阅请求
            BorrowBookDTO borrowDTO = new BorrowBookDTO();
            borrowDTO.setUserId(userId);
            borrowDTO.setBookId(bookId);
            
            // 执行借阅
            return borrowService.borrowBook(borrowDTO);
        } catch (Exception e) {
            log.error("快速借阅图书失败", e);
            return Result.fail("借阅失败：" + e.getMessage());
        }
    }

    /**
     * 快速预约图书
     * 
     * @param userId 用户ID
     * @param bookId 图书ID
     * @return 预约结果
     */
    public Result<ReservationVO> quickReserveBook(String userId, String bookId) {
        log.info("快速预约图书，用户ID：{}，图书ID：{}", userId, bookId);
        
        try {
            // 创建预约请求
            ReservationCreateDTO reservationDTO = new ReservationCreateDTO();
            reservationDTO.setUserId(userId);
            reservationDTO.setBookId(bookId);
            
            // 执行预约
            return reservationService.createReservation(reservationDTO);
        } catch (Exception e) {
            log.error("快速预约图书失败", e);
            return Result.fail("预约失败：" + e.getMessage());
        }
    }

    /**
     * 获取图书馆统计信息
     * 
     * @return 统计信息
     */
    public LibraryStatisticsVO getLibraryStatistics() {
        log.info("获取图书馆统计信息");
        
        LibraryStatisticsVO statistics = new LibraryStatisticsVO();
        
        try {
            // 获取图书统计
            BookQuery bookQuery = new BookQuery();
            PageResult<BookVO> allBooks = bookQueryService.getBookPage(bookQuery);
            statistics.setTotalBooks(allBooks.getTotal());
            
            // 获取作者统计
            AuthorQuery authorQuery = new AuthorQuery();
            PageResult<AuthorVO> allAuthors = authorQueryService.getAuthorPage(authorQuery);
            statistics.setTotalAuthors(allAuthors.getTotal());
            
            // 获取当前借阅统计
            BorrowRecordQuery borrowQuery = new BorrowRecordQuery();
            borrowQuery.setStatus(0); // 借阅中
            PageResult<BorrowRecordVO> currentBorrows = borrowService.getBorrowRecordPage(borrowQuery);
            statistics.setCurrentBorrows(currentBorrows.getTotal());
            
            // 获取当前预约统计
            ReservationQuery reservationQuery = new ReservationQuery();
            reservationQuery.setStatus(0); // 预约中
            PageResult<ReservationVO> currentReservations = reservationService.getReservationPage(reservationQuery);
            statistics.setCurrentReservations(currentReservations.getTotal());
            
            return statistics;
        } catch (Exception e) {
            log.error("获取图书馆统计信息失败", e);
            return new LibraryStatisticsVO();
        }
    }

    // 内部类定义VO对象
    public static class LibrarySearchResultVO {
        private java.util.List<BookVO> books;
        private java.util.List<AuthorVO> authors;
        
        // getters and setters
        public java.util.List<BookVO> getBooks() { return books; }
        public void setBooks(java.util.List<BookVO> books) { this.books = books; }
        public java.util.List<AuthorVO> getAuthors() { return authors; }
        public void setAuthors(java.util.List<AuthorVO> authors) { this.authors = authors; }
    }

    public static class UserLibraryOverviewVO {
        private java.util.List<BorrowRecordVO> currentBorrows;
        private java.util.List<ReservationVO> currentReservations;
        private java.util.List<BookVO> recommendedBooks;
        
        // getters and setters
        public java.util.List<BorrowRecordVO> getCurrentBorrows() { return currentBorrows; }
        public void setCurrentBorrows(java.util.List<BorrowRecordVO> currentBorrows) { this.currentBorrows = currentBorrows; }
        public java.util.List<ReservationVO> getCurrentReservations() { return currentReservations; }
        public void setCurrentReservations(java.util.List<ReservationVO> currentReservations) { this.currentReservations = currentReservations; }
        public java.util.List<BookVO> getRecommendedBooks() { return recommendedBooks; }
        public void setRecommendedBooks(java.util.List<BookVO> recommendedBooks) { this.recommendedBooks = recommendedBooks; }
    }

    public static class LibraryStatisticsVO {
        private Long totalBooks;
        private Long totalAuthors;
        private Long currentBorrows;
        private Long currentReservations;
        
        // getters and setters
        public Long getTotalBooks() { return totalBooks; }
        public void setTotalBooks(Long totalBooks) { this.totalBooks = totalBooks; }
        public Long getTotalAuthors() { return totalAuthors; }
        public void setTotalAuthors(Long totalAuthors) { this.totalAuthors = totalAuthors; }
        public Long getCurrentBorrows() { return currentBorrows; }
        public void setCurrentBorrows(Long currentBorrows) { this.currentBorrows = currentBorrows; }
        public Long getCurrentReservations() { return currentReservations; }
        public void setCurrentReservations(Long currentReservations) { this.currentReservations = currentReservations; }
    }
}
